/**
 * 新闻相关 API
 */
import { get, post } from '../utils/request.js'
import { API_ENDPOINTS } from '../utils/config.js'
import {
  mockNewsList,
  mockComments,
  generateMockPageData,
  mockDelay,
  mockApiResponse
} from '../utils/mockData.js'

// 是否使用模拟数据（在没有后端的情况下）
const USE_MOCK_DATA = false

/**
 * 获取新闻列表
 * @param {Object} params 查询参数
 * @param {number} params.page 页码，从0开始
 * @param {number} params.size 每页大小
 * @param {string} params.sort 排序字段和方向
 * @returns {Promise} 新闻列表
 */
export const getNewsList = async (params = {}) => {
  if (USE_MOCK_DATA) {
    await mockDelay(800) // 模拟网络延迟

    const defaultParams = {
      page: 0,
      size: 10,
      sort: 'publishTime,desc'
    }
    const finalParams = { ...defaultParams, ...params }

    // 模拟搜索功能
    let filteredNews = mockNewsList
    if (finalParams.keyword) {
      filteredNews = mockNewsList.filter(news =>
        news.title.includes(finalParams.keyword) ||
        news.summary.includes(finalParams.keyword)
      )
    }

    const pageData = generateMockPageData(filteredNews, finalParams.page, finalParams.size)
    return mockApiResponse(pageData)
  }

  const defaultParams = {
    page: 0,
    size: 10,
    sort: 'publishTime,desc'
  }
  return get(API_ENDPOINTS.NEWS.LIST, { ...defaultParams, ...params })
}

/**
 * 获取新闻详情
 * @param {number} id 新闻ID
 * @returns {Promise} 新闻详情
 */
export const getNewsDetail = async (id) => {
  if (USE_MOCK_DATA) {
    await mockDelay(600)

    const news = mockNewsList.find(item => item.id === parseInt(id))
    if (news) {
      return mockApiResponse(news)
    } else {
      return mockApiResponse(null, false, '新闻不存在')
    }
  }

  const url = API_ENDPOINTS.NEWS.DETAIL.replace('{id}', id)
  return get(url)
}

/**
 * 点赞新闻
 * @param {number} id 新闻ID
 * @returns {Promise} 点赞结果
 */
export const likeNews = async (id) => {
  if (USE_MOCK_DATA) {
    await mockDelay(300)
    return mockApiResponse({ success: true })
  }

  const url = API_ENDPOINTS.NEWS.LIKE.replace('{id}', id)
  return post(url)
}

/**
 * 获取新闻评论列表
 * @param {number} newsId 新闻ID
 * @param {Object} params 查询参数
 * @param {number} params.page 页码，从0开始
 * @param {number} params.size 每页大小
 * @returns {Promise} 评论列表
 */
export const getNewsComments = async (newsId, params = {}) => {
  if (USE_MOCK_DATA) {
    await mockDelay(500)

    const defaultParams = {
      page: 0,
      size: 20,
      sort: 'createTime,desc'
    }
    const finalParams = { ...defaultParams, ...params }

    // 过滤对应新闻的评论
    const newsComments = mockComments.filter(comment => comment.newsId === parseInt(newsId))
    const pageData = generateMockPageData(newsComments, finalParams.page, finalParams.size)
    return mockApiResponse(pageData)
  }

  const defaultParams = {
    page: 0,
    size: 20,
    sort: 'createTime,desc'
  }
  const url = API_ENDPOINTS.NEWS.COMMENTS.replace('{id}', newsId)
  return get(url, { ...defaultParams, ...params })
}

/**
 * 发表评论
 * @param {number} newsId 新闻ID
 * @param {string} content 评论内容
 * @returns {Promise} 评论结果
 */
export const postComment = async (newsId, content) => {
  if (USE_MOCK_DATA) {
    await mockDelay(800)

    // 模拟创建新评论
    const newComment = {
      id: Date.now(),
      newsId: parseInt(newsId),
      user: {
        id: 999,
        nickname: "当前用户",
        avatarUrl: null
      },
      content,
      likeCount: 0,
      isLiked: false,
      createTime: new Date().toISOString()
    }

    // 添加到模拟数据中
    mockComments.unshift(newComment)

    return mockApiResponse(newComment)
  }

  const url = API_ENDPOINTS.NEWS.COMMENTS.replace('{id}', newsId)
  return post(url, { content })
}

/**
 * 点赞评论
 * @param {number} commentId 评论ID
 * @returns {Promise} 点赞结果
 */
export const likeComment = async (commentId) => {
  if (USE_MOCK_DATA) {
    await mockDelay(300)
    return mockApiResponse({ success: true })
  }

  const url = API_ENDPOINTS.NEWS.COMMENT_LIKE.replace('{id}', commentId)
  return post(url)
}
